package com.celesea.workflow.demo.service;

import com.celesea.framework.service.AbstractBaseService;
import com.celesea.framework.util.CollectionKit;
import com.celesea.framework.util.Page;
import com.celesea.framework.util.PageData;
import com.celesea.framework.util.Sort;
import com.celesea.workflow.demo.entity.Demo;
import com.celesea.workflow.demo.entity.DemoData;
import com.celesea.workflow.demo.entity.DemoPerm;
import com.celesea.workflow.demo.repository.DemoDataRepository;
import com.celesea.workflow.demo.vo.DemoFilter;
import com.celesea.workflow.demo.vo.DemoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author JackYuan
 * @create 2017-11-18 15:40
 */
@Service
public class DemoServiceImpl extends AbstractBaseService<Demo> implements DemoService {

    @Autowired
    private DemoPermService demoPermService;
    @Autowired
    private DemoDataRepository demoDataRepository;

    @Override
    public PageData<DemoVo> selectPage(DemoFilter filter, Page page, Sort sort) {
        PageData<Demo> data = super.selectPage(filter, page, sort);
//        if (CollectionKit.isNotEmpty(data.getDataList())) {
//            List<String> ids = data.getDataList().stream().map(item -> item.getId()).collect(Collectors.toList());
//        }
        //TODO mongo
        return data.convert(item -> {
            // TODO 修改为根据ids批量查询
            DemoVo entity = new DemoVo(item);
            entity.setDemoData(demoDataRepository.findOne(item.getId()));
            return entity;
        });
    }

    @Override
    public DemoVo selectById(String id) {
        Demo demo = super.selectById(id);
        DemoVo demoVo = new DemoVo(demo);
        List<DemoPerm> demoPerms = demoPermService.findByDemo(id);
        DemoData demoData = demoDataRepository.findOne(id);
        demoVo.setDemoData(demoData);
        demoVo.setDemoPerms(demoPerms);
        return demoVo;
    }


    @Override
    public DemoVo insert(DemoVo entity) {
        Demo demo = entity.toEntity();
        super.insert(demo);
        entity.setId(demo.getId());
        demoDataRepository.insert(entity.toEntityData());
        if (CollectionKit.isNotEmpty(entity.getDemoPerms())) {
            demoPermService.insertList(entity.getDemoPerms());
        }
        return entity;
    }


    @Override
    public DemoVo update(DemoVo entity) {
        Demo demo = entity.toEntity();
        super.update(demo);
        demoDataRepository.save(entity.toEntityData());
        demoPermService.deleteByDemo(entity.getId());
        if (CollectionKit.isNotEmpty(entity.getDemoPerms())) {
            demoPermService.insertList(entity.getDemoPerms());
        }
        return entity;
    }
}
